<!--
 * 预警规整配置
-->
<template>
  <div class="warn-mng-config">
    <div class="warn-mng-config__header">预警规则配置</div>
    <div class="warn-mng-config__content">
      <el-divider content-position="left" class="warn-mng-config---content__title">成交规则</el-divider>
      <div class="warn-mng-config---content__item">
        <el-form :model="transactionRulesForm" :rules="transactionRulesFormRules" ref="transactionRulesFormRef">
          <el-form-item label="预警级别" prop="riskLevel">
            <el-radio-group v-model="transactionRulesForm.riskLevel">
              <el-radio label="1">提示</el-radio>
              <el-radio label="2">警告</el-radio>
              <el-radio label="3">封号</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="同一账号当天成交次数" prop="dayNum">
            <el-input-number v-model="transactionRulesForm.dayNum" :step="1" :min="0"></el-input-number>
            （次）
          </el-form-item>
          <el-form-item label="同一账号每周成交次数" prop="weekNum">
            <el-input-number v-model="transactionRulesForm.weekNum" :step="1" :min="0"></el-input-number>
            （次）
          </el-form-item>
          <el-form-item label="同一账号每月成交次数" prop="monthNum">
            <el-input-number v-model="transactionRulesForm.monthNum" :step="1" :min="0"></el-input-number>
            （次）
          </el-form-item>
        </el-form>
      </div>

      <el-divider content-position="left" class="warn-mng-config---content__title">标品购买规则</el-divider>
      <div class="warn-mng-config---content__item">
        <el-form :model="standardRulesForm" :rules="standardRulesFormRules" ref="standardRulesFormRef">
          <el-form-item label="预警级别" prop="riskLevel">
            <el-radio-group v-model="standardRulesForm.riskLevel">
              <el-radio label="1">提示</el-radio>
              <el-radio label="2">警告</el-radio>
              <el-radio label="3">封号</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="list">
            <el-table :data="standardRulesForm.list" border
              :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
              <el-table-column label="序号" type="index" align="center" width="60"></el-table-column>
              <el-table-column label="商品名称" prop="goodsName"></el-table-column>
              <el-table-column label="一次性购买数量（瓶）" prop="singleNum">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.singleNum" :step="1" :min="1" size="mini" />
                </template>
              </el-table-column>
              <el-table-column label="月累计购买数量（瓶）" prop="monthNum">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.monthNum" :step="1" :min="1" size="mini" />
                </template>
              </el-table-column>
              <el-table-column label="操作" :align="'center'" fixed="right" width="160">
                <template slot-scope="scope">
                  <el-button type="text" size="mini"
                    @click="handleDelete(scope.$index, 'standardRulesForm')">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>

        <el-button type="primary" size="mini" @click="handleAdd('standardRulesForm')">添加商品</el-button>
      </div>

      <el-divider content-position="left" class="warn-mng-config---content__title">非标品购买规则</el-divider>
      <div class="warn-mng-config---content__item">
        <el-form :model="nonStandardRulesForm" :rules="nonStandardRulesFormRules" ref="nonStandardRulesFormRef">
          <el-form-item label="预警级别" prop="riskLevel">
            <el-radio-group v-model="nonStandardRulesForm.riskLevel">
              <el-radio label="1">提示</el-radio>
              <el-radio label="2">警告</el-radio>
              <el-radio label="3">封号</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="list">
            <el-table :data="nonStandardRulesForm.list" border
              :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
              <el-table-column label="序号" type="index" align="center" width="60"></el-table-column>
              <el-table-column label="商品名称" prop="goodsName"></el-table-column>
              <el-table-column label="一次性购买数量（瓶）" prop="singleNum">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.singleNum" :step="1" :min="1" size="mini" />
                </template>
              </el-table-column>
              <el-table-column label="月累计购买数量（瓶）" prop="monthNum">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.monthNum" :step="1" :min="1" size="mini" />
                </template>
              </el-table-column>
              <el-table-column label="操作" :align="'center'" fixed="right" width="160">
                <template slot-scope="scope">
                  <el-button type="text" size="mini"
                    @click="handleDelete(scope.$index, 'nonStandardRulesForm')">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-form>

        <el-button type="primary" size="mini" @click="handleAdd('nonStandardRulesForm')">添加商品</el-button>
      </div>
    </div>

    <div class="warn-mng-config__footer">
      <el-button @click="$router.back()">取消</el-button>
      <el-button type="primary" @click="handleSave()" :loading="loading">保存</el-button>
    </div>

    <ShopDialog :show.sync="show" :goodsIds="goodsIds" @confirm="handleConfirm" />
  </div>
</template>

<script>
import ShopDialog from './components/ShopDialog.vue';
import { queryRiskRule, createRiskRule } from '@/api/warningManager';
export default {
  components: {
    ShopDialog
  },
  data() {
    return {
      loading: false,
      transactionRulesForm: {
        ruleName: '成交规则',
        ruleType: 0,
        riskLevel: '',
        dayNum: '',
        weekNum: '',
        monthNum: '',
        goodsId: -1
      },
      standardRulesForm: {
        riskLevel: '',
        list: [],
      },
      nonStandardRulesForm: {
        riskLevel: '',
        list: [],
      },

      transactionRulesFormRules: {
        riskLevel: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
        dayNum: [{ required: true, message: '请输入日累计购买数量', trigger: 'blur' }],
        weekNum: [{ required: true, message: '请输入周累计购买数量', trigger: 'blur' }],
        monthNum: [{ required: true, message: '请输入月累计购买数量', trigger: 'blur' }],
      },

      standardRulesFormRules: {
        riskLevel: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
        list: [{ type: 'array', required: true, message: '请选择商品', trigger: 'change' }],
      },

      nonStandardRulesFormRules: {
        riskLevel: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
        list: [{ type: 'array', required: true, message: '请选择商品', trigger: 'change' }],
      },

      // 弹框相关
      show: false,
      listType: '',
      goodsIds: [],
    };
  },
  created() {
    this.getDetail();
  },
  methods: {
    getDetail() {
      queryRiskRule().then(res => {
        if (res.code == 1) {
          const transactionRule = res.records.find(item => item.ruleType == 0);
          if (transactionRule) {
            this.transactionRulesForm = transactionRule
          }
          this.standardRulesForm.list = res.records.filter(item => item.ruleType == 1);
          this.nonStandardRulesForm.list = res.records.filter(item => item.ruleType == 2);

          if (this.standardRulesForm.list.length > 0) this.standardRulesForm.riskLevel = this.standardRulesForm.list[0].riskLevel;
          if (this.nonStandardRulesForm.list.length > 0) this.nonStandardRulesForm.riskLevel = this.nonStandardRulesForm.list[0].riskLevel;
        }
      })
    },
    handleAdd(type) {
      this.listType = type;
      this.goodsIds = this[type].list;
      this.show = true;
    },
    handleConfirm(data) {
      this[this.listType].list = data.map(item => {
        const existItem = this[this.listType].list.find(i => i.goodsId === item.goodsId);
        return {
          ...item,
          singleNum: existItem ? existItem.singleNum : '',
          monthNum: existItem ? existItem.monthNum : '',
        }
      });

      this.$refs[this.listType + 'Ref'].validate()
    },
    handleDelete(index, type) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this[type].list.splice(index, 1);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      })
    },
    async handleSave() {
      const transactionValidRes = await this.$refs.transactionRulesFormRef.validate()
      const standardValidRes = await this.$refs.standardRulesFormRef.validate()
      const nonStandardValidRes = await this.$refs.nonStandardRulesFormRef.validate()
      Promise.all([transactionValidRes, standardValidRes, nonStandardValidRes]).then(() => {
        const transactionArr = [{ ...this.transactionRulesForm }];
        const standardArr = this.standardRulesForm.list.map(item => {
          return {
            ruleName: '标品购买规则',
            ruleType: 1,
            riskLevel: this.standardRulesForm.riskLevel,
            goodsId: item.goodsId,
            goodsName: item.goodsName,
            singleNum: item.singleNum,
            monthNum: item.monthNum,
          }
        })
        const nonStandardArr = this.nonStandardRulesForm.list.map(item => {
          return {
            ruleName: '非标品购买规则',
            ruleType: 2,
            riskLevel: this.nonStandardRulesForm.riskLevel,
            goodsId: item.goodsId,
            goodsName: item.goodsName,
            singleNum: item.singleNum,
            monthNum: item.monthNum,
          }
        })

        this.loading = true;
        createRiskRule({
          addReqs: [...transactionArr, ...standardArr, ...nonStandardArr]
        }).then(res => {
          if (res.code == 1) {
            this.$message({
              type: 'success',
              message: '保存成功!'
            });

            this.$router.back();
          }
        }).finally(() => {
          this.loading = false;
        })
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.warn-mng-config {
  display: flex;
  flex-direction: column;
  gap: 15px;
  height: inherit;
  width: 100%;

  &__header {
    font-size: 16px;
    font-weight: 600;
  }

  &__content {
    flex: 1;
    overflow: auto;

    &__title {
      font-size: 16px;
      font-weight: 600;
      color: #2b7dbc;
    }

    &__item {}
  }
}
</style>
